package com.imooc.classloader;

import java.io.*;

/**
 * @ClassName MyClassLoader
 * @Description From: https://www.imooc.com/video/16059
 * 自定义Java类加载器来实现Java类的热加载！
 *
 * @Author Wxg
 * @Date 2018/11/15 1:00
 * @Version 1.0
 */
public class MyClassLoader extends ClassLoader{

    // 欲加载的Java类的路径
    private String classpath;

    public MyClassLoader(String classpath) {
        super(ClassLoader.getSystemClassLoader());
        this.classpath = classpath;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] data = loadClassData(name);
        return this.defineClass(name, data, 0, data.length);
    }

    private byte[] loadClassData(String name) {
        name = name.replace(".", "/");
        byte[] returnBytes = null;
        try {
            FileInputStream is = new FileInputStream(new File(classpath + name + ".class"));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            int b;
            while ((b = is.read()) != -1) {
                baos.write(b);
            }
            returnBytes = baos.toByteArray();
            is.close();
            baos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return returnBytes;
    }
}
